package com.wlstock.funi.runnable;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.dao.StrategyFundSelDao;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.ToastUtils;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * 这个暂时用来维持会话使用，同时也可以获取到账号的持仓数据，如果之后需要可以拿来做每天开盘以及收盘的初始化操作
 */
public class RefreshLogSession {

	public static RefreshLogSession instance;
	private ResultListener listener;

	private RefreshLogSession(){};

	public static  RefreshLogSession getInstance(){
		if (instance == null){
			synchronized (RefreshLogSession.class){
				instance = new RefreshLogSession();
			}
		}
		return instance;
	}

	public void refresh(final ResultListener listener){
		this.listener = listener;
		FundAsyTask<Void, Void, Object> fundAsyTask = new FundAsyTask<>();
		fundAsyTask.backListener = new FundAsyTask.TaskLitener<Void, Object>() {
			@Override
			public Object doInBackground(Void... params) {
				HttpClient client = new DefaultHttpClient();
				try {
					HttpGet hGet = new HttpGet("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getStockPosition");
					hGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
					hGet.addHeader("Accept-Encoding","gzip, deflate, sdch");
					hGet.addHeader("Cache-Control","max-age=0");
					hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
					hGet.addHeader("Connection","keep-alive");
					hGet.addHeader("Cookie",FundApplication.cookie);

					hGet.addHeader("Upgrade-Insecure-Requests","1");
					hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");

					HttpResponse response = client.execute(hGet);
					if (response.getStatusLine().getStatusCode() == 200) {
						String is2Str = IOUtils.is2Str(response.getEntity().getContent());
						return is2Str;
					}
					return null;
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {

					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};
		fundAsyTask.resultListener = new FundAsyTask.TaskResultListener<Object>() {
			@Override
			public void onPostResult(Object o) {
				if (o!=null){
					String is2Str = (String)o;
					Document doc = Jsoup.parse(is2Str);
					Elements storeEles = doc.select("[align=\"right\"]");
					//				MyAccountStockDao.getInstance(FundApplication.getInstance()).deleteAllStocks();
					MyAccountStockDao.getInstance(FundApplication.getInstance()).deleteInvalidStks();
					for (Element item : storeEles) {
						Elements itemElements = item.children();
						if (itemElements.size()!=14 ) {
							continue;
						}
//						<th>操作</th>
//						<th>证券代码</th>
//						<th>证券名称</th>
//						<th>参考持股</th>
//						<th>股份余额</th>
//						<th>可用股份</th>
//						<th>成本价</th>
//						<th>当前价</th>
//						<th>当前成本</th>
//						<th>最新市值</th>
//						<th>浮动盈亏</th>
//						<th>盈亏比例(%)</th>
//						<th>股东代码</th>
//						<th>资金帐号</th>

//						<td>操作</td>
//						<td>000691</td>
//						<td>ST亚太</td>
//						<td>2600.00</td>
//						<td>2600.00</td>
//						<td>2600.00</td>
//						<td>8.433</td>
//						<td>8.3900</td>
//						<td>21924.58</td>
//						<td>21814.00</td>
//						<td>-110.58</td>
//						<td>-0.51</td>
//						<td>0186265187</td>
//						<td>880000910112</td>

						String stkCode = itemElements.get(1).childNodes().get(0).toString();  //编码
						String stkName = itemElements.get(2).childNodes().get(0).toString();//名称
						Float pty    =  Float.valueOf(itemElements.get(5).childNodes().get(0).toString()); //可用持仓
						String buyPrice    = itemElements.get(6).childNodes().get(0).toString();//成本价
						String curPrice    = itemElements.get(7).childNodes().get(0).toString();//当前价
						float cost  = Float.valueOf(itemElements.get(8).childNodes().get(0).toString());//当前成本
						float marketPrice   = Float.valueOf(itemElements.get(9).childNodes().get(0).toString());//最新市值
						float profitMoney  = Float.valueOf(itemElements.get(10).childNodes().get(0).toString());//盈亏金额
						float profitRate   = Float.valueOf(itemElements.get(11).childNodes().get(0).toString());//盈亏比例




						//去除1天报价那些
						if (StockUtils.isStkValid(stkCode)){
							MyAccountStocks tmpStock = MyAccountStockDao.getInstance(FundApplication.getInstance()).queryStock(stkCode);
							if (tmpStock != null) {
								tmpStock.setFileds(stkCode, stkName, Math.round(pty), buyPrice, curPrice,cost,marketPrice ,profitRate, profitMoney);
							}else {
								tmpStock = new MyAccountStocks(stkCode, stkName, Math.round(pty), buyPrice, curPrice,cost,marketPrice, profitRate, profitMoney);
							}
							//这两个方法暂时隐藏
							//tmpStock.setTargetDaysCount(StrategyFundSelDao.getInstance(FundApplication.getInstance()).queryShouldKeepDays(tmpStock.getStkCode()));
							tmpStock.setWithStraModel(StrategyFundSelDao.getInstance(FundApplication.getInstance()).queryStraModelWithCode(tmpStock.getStkCode()));
							MyAccountStockDao.getInstance(FundApplication.getInstance()).createOrUpdateStock(tmpStock);
							SelfFundDao.getInstance(FundApplication.getInstance()).addWithMyAccountStock(tmpStock);
						}
					}
					ToastUtils.showMiddleMsg(FundApplication.getInstance(), "更新会话成功");
					if (listener!=null){
						listener.resultSuccess();
					}
				}else{
					FundApplication.isLogSuccess = false;
					NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "访问刷新接口失败", R.drawable.ic_exception);
					if (listener!=null){
						listener.resultFaile();
					}
				}
			}
		};
		fundAsyTask.execute();
	}

//	https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getFunds
	
//	Accept:*/*
//	Accept-Encoding:gzip, deflate
//	Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
//	Connection:keep-alive
//	Content-Length:0
//	Content-Type:text/plain;charset=UTF-8
//	Cookie:JSESSIONID=gjHjWkvJYdqrV9pbZn9bvS1WsFxLGgLjXvtP1DQvGBkl6B1nQtBR!297676372!-908755652; ssl=etrade-ssl-1
//	Host:etrade.cs.ecitic.com
//	Origin:https://etrade.cs.ecitic.com
//	Referer:https://etrade.cs.ecitic.com/ymtrade/stock/cxzc.jsp
//	User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
//	X-Requested-With:XMLHttpRequest

	public interface  ResultListener{
		public void resultSuccess();
		public void resultFaile();
	}

}
